package com.sitanyun.merchant.guide.frament.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.adapter.SwichsAdapter;
import com.sitanyun.merchant.guide.adapter.SwishShopAdapter;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.bean.AccountBean;
import com.sitanyun.merchant.guide.bean.SwiShopsBean;
import com.sitanyun.merchant.guide.bean.SwishShopBean;
import com.sitanyun.merchant.guide.bean.UserInfo;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.presenter.impl.SwitchstoresAPresenterImpl;
import com.sitanyun.merchant.guide.frament.presenter.inter.ISwitchstoresAPresenter;
import com.sitanyun.merchant.guide.frament.view.inter.IMyFView;
import com.sitanyun.merchant.guide.frament.view.inter.ISwitchstoresAView;
import com.sitanyun.merchant.guide.signature.GenerateTestUserSig;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.view.activity.LoginActivity;
import com.sitanyun.merchant.guide.weiht.Aes;
import com.sitanyun.merchant.guide.weiht.SPutils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.qcloud.tuicore.TUILogin;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 切换门店
 */
public class SwitchstoresActivity extends BaseActivity implements ISwitchstoresAView {

    @BindView(R.id.tv_return)
    ImageView tvReturn;
    @BindView(R.id.tv_title_str)
    TextView tvTitleStr;
    @BindView(R.id.image_right_key)
    ImageView imageRightKey;
    @BindView(R.id.tv_right_key)
    TextView tvRightKey;
    @BindView(R.id.ff_main_layout)
    FrameLayout ffMainLayout;

    @BindView(R.id.shop_inter)
    TextView shopInter;
    @BindView(R.id.switch_rec)
    ListView switchRec;
    @BindView(R.id.sms_login)
    TextView smsLogin;
    private ISwitchstoresAPresenter mISwitchstoresAPresenter;
    private SwishShopAdapter swishShopAdapter;
    private SwishShopBean swishShopBean;
    private int selectPosition = -1;//用于记录用户选择的变量
    private List<SwishShopBean.DataBean> data = new ArrayList<>();
    private SwichsAdapter swichsAdapter;
    private String nodeId="";
    private String staffId="";
    private String userid;
    private String cid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mISwitchstoresAPresenter = new SwitchstoresAPresenterImpl(this);
        mISwitchstoresAPresenter.getswich();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_switchstores;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        setFindViewById(true);

      //  setTitleStr("我的门店");

    }

    @Override
    public void initView() {
        userid = SharedPreferenceUtil.getStringData("userid");
        cid = SharedPreferenceUtil.getStringData("cid");
        //设置点击事件
        switchRec .setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //调用适配器中的setposition方法，把点击的positon传过去
                swichsAdapter.setPosition(position);
                nodeId = swishShopBean.getData().get(position).getNodeId();
                staffId = swishShopBean.getData().get(position).getStaffId();
                //刷新适配器
                swichsAdapter.notifyDataSetChanged();
            }
        });

    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IMyFView.RESPONSE_ONE) {
            swishShopBean = (SwishShopBean) response;
            if (swishShopBean.getCode() == 0) {
                if (swishShopBean.getData().size() != 0) {
                    data.addAll(swishShopBean.getData());
                    swichsAdapter = new SwichsAdapter(SwitchstoresActivity.this, data);
                    switchRec.setAdapter(swichsAdapter);
                    if (SharedPreferenceUtil.getStringData("nodeid").equals(SharedPreferenceUtil.getStringData("tonodeid"))){
                        setTitleStr("我的商户");
                        shopInter.setText("当前共"+swishShopBean.getData().size()+"个商户");
                    }else {
                        setTitleStr("我的门店");
                        shopInter.setText("当前共"+swishShopBean.getData().size()+"个门店");
                    }
                  //  shopInter.setText("当前共"+swishShopBean.getData().size()+"个门店");

                } else {
                    //错误
                    shopInter.setText("当前共0个门店");
                }

            } else {
                ///无数据
           //     ToastUtil.showToast(SwitchstoresActivity.this, swishShopBean.getMsg() + "");
                shopInter.setText("当前共0个门店");
            }
        }
    }

    /**
     * 门店
     * @param response
     * @param responseFlag
     * @param <T>
     */
    @Override
    public <T> void responseshop(T response, int responseFlag) {
        if (responseFlag == ISwitchstoresAView.RESPONSE_ONE) {
            SwiShopsBean loginBean = (SwiShopsBean) response;
            if (loginBean.getCode() == 0) {
                SharedPreferenceUtil.SaveData("nodename", loginBean.getNode_name());
                SharedPreferenceUtil.SaveData("userid", loginBean.getUser_id());
                SharedPreferenceUtil.SaveData("tonodename", loginBean.getTop_node_name()+"");
                SharedPreferenceUtil.SaveData("token", loginBean.getAccess_token());
                SharedPreferenceUtil.SaveData("staffid", loginBean.getStaff_id());
                SharedPreferenceUtil.SaveData("clientid", loginBean.getS_client_id());
                SharedPreferenceUtil.SaveData("nodeid",loginBean.getNode_id());
                SharedPreferenceUtil.SaveData("tonodeid", loginBean.getTop_node_id());
                SharedPreferenceUtil.SaveData("sxtoken", loginBean.getRefresh_token());
                SharedPreferenceUtil.SaveData("cid", loginBean.getS_client_id());
                SharedPreferenceUtil.SaveData("staffname", loginBean.getStaff_name());
                // 获取userSig函数
                String userSig = GenerateTestUserSig.genTestUserSig("staffid_"+loginBean.getStaff_id());
                TUILogin.login("staffid_"+loginBean.getStaff_id(), userSig, new V2TIMCallback() {
                    @Override
                    public void onError(final int code, final String desc) {
                    }

                    @Override
                    public void onSuccess() {
                        //   ToastUtil.showToast(MainActivity.this,"腾讯云注册成功");
                        UserInfo.getInstance().setAutoLogin(true);
                        finish();
                    }
                });

            } else {
               ToastUtil.showToast(SwitchstoresActivity.this,"数据错误");
            }

        }
    }

    /**
     * 确定
     */
    @OnClick(R.id.sms_login)
    public void onViewClicked() {
       if (nodeId.isEmpty()||staffId.isEmpty()){
            finish();
           return;
       }

        if (SharedPreferenceUtil.getStringData("nodeid").equals(SharedPreferenceUtil.getStringData("tonodeid"))){
            OkHttpUtils.delete().url(Urls.logout)
                    .addHeader("Content-Type","application/x-www-form-urlencoded")
                    .addHeader("Authorization","Bearer"+ SharedPreferenceUtil.getStringData("token"))
                    .build().execute(new StringCallbacks() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(String response, int id) {
                    AccountBean accountBean  = new Gson().fromJson(response, AccountBean.class);
                    if (accountBean.getCode()==0){
                        Aes mAes = new Aes();
                        try {
                            String secret=  cid+","+nodeId+","+staffId+","+userid;
                            byte[]  secrets = secret.getBytes("UTF8");
                            String   secretaec = mAes.encrypt(secrets);//加密
                            mISwitchstoresAPresenter.getswichsave(staffId,userid,cid,nodeId,secretaec);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            });

        }else {

            OkHttpUtils.delete().url(Urls.forcelogout)
                    .addHeader("Content-Type","application/x-www-form-urlencoded")
                    .addHeader("Authorization","Bearer"+ SharedPreferenceUtil.getStringData("token"))
                    .build().execute(new StringCallbacks() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(String response, int id) {
                    AccountBean accountBean  = new Gson().fromJson(response, AccountBean.class);
                    if (accountBean.getCode()==0){
                        Aes mAes = new Aes();
                        try {
                            String secret=  cid+","+nodeId+","+staffId+","+userid;
                            byte[]  secrets = secret.getBytes("UTF8");
                            String   secretaec = mAes.encrypt(secrets);//加密
                            mISwitchstoresAPresenter.getswichsave(staffId,userid,cid,nodeId,secretaec);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            });

        }




    }
}
